package org.gicentre.tweet;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;


/**Generates access keys
 * 
 * @author Aidan Slingsby, giCentre, based on Twitter4j documentation
 *
 */
public class TwitterAuth {
	public static void main(String args[]) throws Exception{

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		System.out.println("Paste application key:");
		String appKey=br.readLine();

		System.out.println("Paste application secret:");
		String appSecret=br.readLine();

		Twitter twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(appKey,appSecret);

		RequestToken requestToken = twitter.getOAuthRequestToken();
		AccessToken accessToken = null;
		while (null == accessToken) {
			System.out.println("Open the following URL and grant access to your account:");
			System.out.println(requestToken.getAuthorizationURL());
			System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
			String pin = br.readLine();
			try{
				if(pin.length() > 0){
					accessToken = twitter.getOAuthAccessToken(requestToken, pin);
				}
				else{
					accessToken = twitter.getOAuthAccessToken();
				}
			}
			catch (TwitterException e) {
				if(401 == e.getStatusCode()){
					System.out.println("Unable to get the access token.");
				}
				else{
					e.printStackTrace();
				}
			}
		}

		System.out.println("accessToken:  "+accessToken.getToken());
		System.out.println("accessSecret: "+accessToken.getTokenSecret());
	}
}
